#include <stdio.h>
#include "iic.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/i2c.h"
#include "string.h"


esp_err_t iic_init(void)
{
    int i2c_master_port = I2C_MASTER_NUM;

    i2c_config_t conf = {
        .mode = I2C_MODE_MASTER,
        .sda_io_num = I2C_MASTER_SDA_IO,
        .scl_io_num = I2C_MASTER_SCL_IO,
        .sda_pullup_en = GPIO_PULLUP_ENABLE,
        .scl_pullup_en = GPIO_PULLUP_ENABLE,
        .master.clk_speed = I2C_MASTER_FREQ_HZ,
    };

    i2c_param_config(i2c_master_port, &conf);

    esp_err_t res = i2c_driver_install(i2c_master_port, conf.mode, I2C_MASTER_RX_BUF_DISABLE, I2C_MASTER_TX_BUF_DISABLE, 0);
    if(res == ESP_OK)
    {
        printf("iic init sucess\r\n");
    }
    else 
    {
        printf("iic init failed\r\n");
    }
    return res;
}

/*
 * @arg: sensor_addr: 该变量为不带最低读写位的地址
*/
esp_err_t iic_write(uint8_t sensor_addr,uint8_t reg_addr, uint8_t* data, uint8_t length)
{
    int ret;
    uint8_t write_buf[20];

    write_buf[0] = reg_addr;
    memcpy(write_buf + 1, data, length);

    ret = i2c_master_write_to_device(I2C_MASTER_NUM, sensor_addr, write_buf, length + 1, I2C_MASTER_TIMEOUT_MS / portTICK_RATE_MS);

    return ret;
}

/*
 * @arg: sensor_addr: 该变量为不带最低读写位的地址
*/
esp_err_t iic_read(uint8_t sensor_addr,uint8_t reg_addr, uint8_t* data, uint8_t length)
{
    return i2c_master_write_read_device(I2C_MASTER_NUM, sensor_addr, &reg_addr, 1, data, length, I2C_MASTER_TIMEOUT_MS / portTICK_RATE_MS);
}
